package utils;

import java.io.IOException;
import java.security.PrivateKey;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import cfca.sm2rsa.common.PKIException;
import cfca.util.KeyUtil;
import cfca.x509.certificate.X509Cert;
import cfca.x509.certificate.X509CertHelper;


/**
 * @title:
 * @description:
 * @author:Administrator
 * @since:
 * @version:
 */
public class MapCache {
	
	/**
	 * 缓存证书
	 */
	private static X509Cert cmbcCert = null;
	/**
	 * 缓存证书MAP
	 */
	private static Map<String, X509Cert> custPubCert = new ConcurrentHashMap<String, X509Cert>();
	private static Map<String, PrivateKey> custPrivCert = new ConcurrentHashMap<String, PrivateKey>();
	
	private static String certPath = PropUtils.getProperty("cert_path");
	/**
	 * 获取平台私钥
	 * @param sm2Path
	 * @param sm2Pass
	 * @return
	 * @throws Exception
	 */
	public static PrivateKey getCustPrivateKey(String secuNo) throws Exception{

		PrivateKey priKey = custPrivCert.get(secuNo);
		if (null != priKey){
			return priKey;
		}else{
			String sm2Pass = Constants.certPassMap.get(secuNo);
			String sm2Path = certPath + secuNo + ".sm2";
			Resource baseResource = new DefaultResourceLoader().getResource(sm2Path);
			String path = baseResource.getURI().getPath();
			priKey = KeyUtil.getPrivateKeyFromSM2(path, sm2Pass);
			custPrivCert.put(secuNo, priKey);
			return priKey;
		}
	}
	
	/**
	 * 获取证书
	 * @param custNo 商户号
	 * @return 私钥
	 * @throws Exception 
	 */
	public static X509Cert getCustCert(String secuNo) throws Exception {
		X509Cert cert = custPubCert.get(secuNo);
		if (null != cert ) {
//			System.out.println("从缓存中读取cert。。。");
			return cert;
		} else { 
			//clearCertByCustNo(custNo);
			try {
				String sm2Path = certPath + secuNo + ".cer";
				Resource baseResource = new DefaultResourceLoader().getResource(sm2Path);
				String path = baseResource.getURI().getPath();
				cert = X509CertHelper.parse(path);
			} catch (PKIException e) {
				e.printStackTrace();
				return null;
			}
			if (null == cert) {
			}
			// 将结果放入缓存
			custPubCert.put(secuNo, cert);
			return cert;
		}
	 
	}

	/**
	 * 从SM2中获取证书
	 * @param sm2Path
	 * @return X509Cert
	 * @throws IOException 
	 */
	public static X509Cert getCMBCCert() throws IOException {
		if (null != cmbcCert){
			return cmbcCert;
		} else{
			try {
				String sm2Path = certPath + "cmbcTest.cer";
				Resource baseResource = new DefaultResourceLoader().getResource(sm2Path);				
				cmbcCert = new X509Cert(baseResource.getInputStream());
			} catch (PKIException e) {
				e.printStackTrace();
			} 			
			return cmbcCert;
		}
	}
	
}

